package main

import (
	_ "gis-server/routers"
	"os"

	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	beecontext "github.com/beego/beego/v2/server/web/context"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	if beego.BConfig.RunMode == "dev" {
		beego.BConfig.WebConfig.DirectoryIndex = true
		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
		orm.Debug = true
	}
	cors := func(ctx *beecontext.Context) {
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")                                                     // 允许访问所有域
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")                          // 允许的访问方法
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization") // 允许的header的类型
		ctx.ResponseWriter.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")

		// 如果是OPTIONS请求，则返回200状态码
		if ctx.Request.Method == "OPTIONS" {
			ctx.ResponseWriter.WriteHeader(200)
			return
		}
	}
	beego.InsertFilter("*", beego.BeforeRouter, cors)
	sqlConn := readMysqlConfFromEnv()
	orm.RegisterDataBase("default", "mysql", sqlConn)
	beego.Run()
}

func readMysqlConfFromEnv() string {
	mysqlUser := os.Getenv("MYSQL_USER")
	mysqlPassword := os.Getenv("MYSQL_PASSWORD")
	mysqlHost := os.Getenv("MYSQL_HOST")
	mysqlPort := os.Getenv("MYSQL_PORT")
	MYSQL_DATABASE := os.Getenv("MYSQL_DATABASE")
	if mysqlUser == "" {
		sqlConn, err := beego.AppConfig.String("sqlconn")
		if err != nil {
			panic(err)
		}
		return sqlConn
	} else {
		return mysqlUser + ":" + mysqlPassword + "@tcp(" + mysqlHost + ":" + mysqlPort + ")/" + MYSQL_DATABASE + "?charset=utf8"
	}
}
